import asyncRoutes from '@/router/asyncRoutes'
import constantRoutes from '@/router/constantRoutes'
import { getRoles, getRole } from '@/api/role' //20230613 获取所有permission

var userRoutes = [
  {
    name: 'trainInfo',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'personInfo',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'gis',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'stationMap',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'playback',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'task',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'event',
    children: [
      {
        name: 'index',
        children: []
      }
    ]
  },
  {
    name: 'maintenance',
    children: [
      {
        name: 'organization',
        children: []
      },
      {
        name: 'account',
        children: [
          {
            name: 'user',
            children: []
          },
          {
            name: 'role',
            children: []
          },
          {
            name: 'source',
            children: []
          }
        ]
      },
      {
        name: 'device',
        children: [
          {
            name: 'handheld',
            children: []
          },
          {
            name: 'position',
            children: []
          },
          {
            name: 'onboard',
            children: []
          }
        ]
      },
      {
        name: 'STPStation',
        children: []
      },
      {
        name: 'systemState',
        children: [   {
          name: 'STPStation',
          children: []
        },
        {
          name: 'serverLink',
          children: []
        },
      ]
      },
      {
        name: 'group',
        children: []
      },
      {
        name: 'train',
        children: []
      },
      {
        name: 'update',
        children: [   {
          name: 'apk',
          children: []
        }]
      },
    ]
  },
  {
    name: '*',
    children: []
  }
]
var op_perm = []


/**
 * 将permission这个tree里面的重复项进行合并，神仙代码 20230614
 * @param tree
 */
function mergeTree(tree) {
  const map = new Map();
  const mergedTree = [];

  function mergeNode(node) {
    const existing = map.get(node.name);
    if (existing) {
      existing.children = mergeChildren(existing.children, node.children);
    } else {
      const copy = { ...node };
      map.set(copy.name, copy);
      mergedTree.push(copy);
    }
  }

  function mergeChildren(arr1, arr2) {
    const map = new Map();
    const mergedChildren = [];

    function mergeChild(child) {
      const existing = map.get(child.name);
      if (existing) {
        existing.children = mergeChildren(existing.children, child.children);
      } else {
        const copy = { ...child };
        map.set(copy.name, copy);
        mergedChildren.push(copy);
      }
    }

    arr1 && arr1.forEach(mergeChild);
    arr2 && arr2.forEach(mergeChild);

    return mergedChildren;
  }

  tree.forEach(mergeNode);

  return mergedTree;
}

async function setRoles(roles) {
  let roleRes = await getRole(roles)
  userRoutes = roleRes.data.permission
  op_perm = roleRes.data.op_perm
}


/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */

function hasPermission(userRoutes, route) {
  for (let index = 0; index < userRoutes.length; index++) {
    const element = userRoutes[index]
    if (route.path.includes(element.name)) {
      return element
    }
  }
  return ''
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutes(routes, userRoutes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    let result = hasPermission(userRoutes, tmp)
    if (result !== '') {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, result.children)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  op_perm: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES: (state, routes) => {
    state.addRoutes = []
    state.routes = []
  },
  SET_OP_PERMS: (state, op_perm) => {
    state.op_perm = op_perm
  },
  RESET_OP_PERMS: (state, op_perm) => {
    state.op_perm = []
  },
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(async resolve => {
      await setRoles(roles)
      let accessedRoutes = filterAsyncRoutes(asyncRoutes, userRoutes)
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_OP_PERMS', op_perm)
      resolve(accessedRoutes)
    })
  },
  clearRoutes({ commit }){
    return new Promise(async resolve => {
      commit('RESET_ROUTES')
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
